import datetime
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import UserProfile
from .forms import UserProfileForm
import random, time

def login(request, user):
    s = 'qwertyuiopasdfghjklzxcvbnm1234567890'
    ticket = ''
    for i in range(15):
        # 获取随机字符串
        ticket += random.choice(s)
    now_time = int(time.time())
    ticket = 'TK_' + ticket + str(now_time)
    request.session['ticket'] = ticket
    user.ticket = ticket
    user.save()


def logout(request):
    request.session.flush()

def login_required(func):

    def wrapper(*args, **kwargs):
        request = args[0]
        is_login = request.session.get('ticket')
        if not is_login:
            return redirect('userprofile:index')
        else:
            result = func(*args, **kwargs)
            return result
    return wrapper


def index(request):
    if request.method == 'POST':
        user_profile_forms = UserProfileForm(data=request.POST)
        if user_profile_forms.is_valid():
            data = user_profile_forms.cleaned_data
            user = UserProfile.objects.filter(username=data['username'], password__endswith=data['password'])[0]
            if user:
                login(request, user)
                return redirect('userprofile:show')
            else:
                return HttpResponse("输入的姓名或身份证号有误，请重新输入~")

    elif request.method == 'GET':
        return render(request, 'index.html')

@login_required
def show(request):
    ticket = request.session.get('ticket')
    user = UserProfile.objects.get(ticket=ticket)
    user.is_read = True
    user.read_time = datetime.datetime.now()
    user.save()
    print("我是展示页面")
    return render(request, 'show.html')

def out(request):
    logout(request)
    return redirect('userprofile:index')